<?php


namespace App\HttpController;


use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Http\Message\Status;
use EasySwoole\VerifyCode\Conf;

class Upload extends \App\Base\ViewController
{
    public function index()
    {
        $this->getView()->assign(['server'=>'http://192.168.56.101:9501/upload/begin']);
        $this->fetch('index');
    }

    public function begin(){
        //https://www.easyswoole.com/HttpServer/uploadFile.html
        //[2019-12-10 15:13:53 #3175.0]	WARNING	swPort_onRead_http: Content-Length is too big, MaxSize=[2096591]
        /*
data: (binary)
name: MX-19_x64.iso
total: 713
index: 1
fileSize: 1495269376
        */
        $request=  $this->request();
        $data = $request->getUploadedFile('data')->getStream();
        $name=$request->getRequestParam('name');
        $total=$request->getRequestParam('total');
        $index=$request->getRequestParam('index');
        $fileSize=$request->getRequestParam('fileSize');

        $file=$name;
        //如果第一次上传的时候，该文件已经存在，则删除文件重新上传
        if($index==1 && file_exists($file) && filesize($file)==$fileSize){
            unlink($file);
        }
        //合并文件
        file_put_contents($file, $data, FILE_APPEND);

        //最后一块时
        if($index==$total){
            
        }

        $this->writeJson(Status::CODE_OK, ['status'=>'ok'], 'success');
    }

    protected function actionNotFound(?string $action)
    {
        $this->response()->withStatus(404);
        $file = EASYSWOOLE_ROOT.'/vendor/easyswoole/easyswoole/src/Resource/Http/404.html';
        if(!is_file($file)){
            $file = EASYSWOOLE_ROOT.'/src/Resource/Http/404.html';
        }
        $this->response()->write(file_get_contents($file));
    }
    
}